<template>

    <div class="template-search-product" :class="{active:visible}">
        <p class="popper-name">
            <strong v-if="selected" v-text=selected.name></strong>
            <span v-else>Product</span>
            <i v-if="!selected"><svg-icon name="tree-down" /></i>
            <i v-else @click="selected && setSelect()"><svg-icon name="select-clear" /></i>
        </p>
        <div class="popper-content">

            <UxLoading v-if="loading" :loading="loading" />

            <div class="template-product-nodata" v-else-if="productList.length == 0">No results found.</div>

            <template v-else>
                <div class="template-product-aside">
                    <dl v-for="group in classifyUsed" :key="group.classify_id">
                        <dt v-text=group.name></dt>
                        <dd v-for="child in group.child" :key="child.classify_id" :class="{active:query.classify == child.classify_id}" @click="setClassify(child)" v-text="child.name"></dd>
                    </dl>
                </div>

                <div class="template-product-list">
                    <ul>
                        <li v-for="item in productList" :key="item.id" :spu="item.spu" @click="setSelect(item)">
                            <figure><img v-lazy="$getImageUrl(item.img_url, 'largest')" /></figure>
                            <h3 v-text="item.name"></h3>
                            <CommonLevelDiscount :price="item.price" :level="item" type="unit|original|discount|icon" />
                            <p name="size" v-text="getSizeFormat(item)"></p>
                            <p name="color"><em v-for="(color, idx) in item.color" :key="idx" :style="{ backgroundColor: color }"></em></p>
                        </li>
                    </ul>
                </div>
            </template>

        </div>
    </div>

</template>
<script>
import { createPopper } from '@popperjs/core';
import { mapGetters } from "vuex";
export default {
    props: {
        value: { type: [String, Number], default: '' },
    },
    data () {
        return {
            instance: null,
            popper: null,
            visible: false,
            loading: true,
            query: { limit: 6, page: 1, classify: '' },
            list: [],
        };
    },
    computed: {
        ...mapGetters("common", {
            classify: "getProductClassify",
        }),

        // 已经使用的分类
        classifyUsed () {
            const result = []
            const classify_map = new Map(this.list.map(i => [i.classify, true]))
            this.classify.map(group => {
                const used = group.child.filter(i => classify_map.get(i.classify_id))
                if (used.length > 0) {
                    result.push({
                        ...group,
                        child: used,
                    })
                }
            })
            return result
        },

        selected () {
            return this.value ? this.list.find(i => i.spu == this.value) : null;
        },
        productList () {
            return this.list.filter(i => i.classify == this.query.classify);
        },
    },

    methods: {

        // 获取列表
        async getList () {
            this.loading = true
            const res = await this.$http("storeTemplate.getTemplateProduct");
            this.loading = false
            this.list = res.data || [];
            this.query.classify = ((this.classifyUsed[0] || { child: [] }).child[0] || {}).classify_id || ''
        },

        onClick (event) {
            const contains = this.$el.contains(event.target)
            if (contains && event.target.closest('.template-search-product .popper-name')) {
                event.stopPropagation();
                event.preventDefault();
                this.visible ? this.onHide() : this.onShow();
            } else if (contains && event.target.closest('.template-search-product .popper-content')) {
                // 对话框中的，不管
                event.stopPropagation();
                event.preventDefault();
            } else {
                this.onHide()
            }
        },


        getSizeFormat (item) {
            let sizeMin = item.size[0];
            let sizemax = item.size[item.size.length - 1];

            if (!sizeMin && !sizemax) {
                return "- -";
            } else if (sizeMin == sizemax) {
                return sizeMin;
            } else {
                return sizeMin + "-" + sizemax;
            }

        },

        setClassify (child) {
            this.query.classify = child.classify_id
            this.query.page = 1;
        },

        setSelect (item) {
            if (item) {
                this.$emit('input', item.spu)
                this.$emit('change', item.spu)
                this.onHide();
            } else {
                this.$emit('input', '')
                this.$emit('change', '')
                this.onHide();
            }
        },

        // 显示
        onShow () {
            if (this.popover) {
                this.visible = true;
                this.popover.removeAttribute("hidden");
                this.instance && this.instance.update();
            } else {
                const button = this.$el.querySelector('.popper-name');
                const content = this.$el.querySelector('.popper-content');

                this.visible = true;
                this.popover = content
                this.instance = createPopper(button, content, {
                    placement: 'bottom',
                    strategy: 'absolute',
                    modifiers: [
                        {
                            name: 'flip',
                            options: {
                                fallbackPlacements: ['top', 'bottom']
                            }
                        },
                        {
                            name: 'offset',
                            options: {
                                offset: [10, 10],
                            },
                        },
                        // {
                        //     name: 'preventOverflow',
                        //     options: { padding: 10 }
                        // }
                    ]
                });
            }
        },

        // 隐藏
        onHide () {
            if (this.popover) {
                this.visible = false;
                this.popover.setAttribute("hidden", "");
            }
        },


    },
    created () {
        this.getList()
    },
    mounted () {
        window.addEventListener('click', this.onClick)
    },
    beforeDestroy () {
        window.removeEventListener('click', this.onClick)
    }
};
</script>
<style lang="scss" scoped>
.template-search-product {
    position: relative;
    height: 40px;

    .popper-content {
        position: absolute;
        z-index: 1;
        top: 100%;
        opacity: 0;
        pointer-events: none;
    }

    &.active {
        & > .popper-name {
            border-color: #f6b2cd;
            box-shadow: 0 0 1px 1px #f6b2cd;
            span {
                color: #000;
                & + i {
                    transform: rotate(180deg);
                }
            }
        }

        & > .popper-content {
            pointer-events: all;
            opacity: 1;
        }
    }
}

.popper-name {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    padding: 0 12px;
    flex: 1;
    background-color: #fff;
    border: 1px solid #e6e6e6;
    box-sizing: border-box;
    border-radius: 8px;
    transition: all 0.2s;
    overflow: hidden;
    cursor: pointer;
    span {
        flex: 1;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #757575;
    }

    strong {
        width: 100%;
        overflow: hidden;
        position: relative;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        white-space: nowrap;
        & + i {
            color: #909090;
            min-width: 14px;
            width: 14px;
            height: 14px;
            &:hover {
                color: #000;
            }
        }
    }

    i {
        min-width: 12px;
        width: 12px;
        height: 12px;
        transition: all 0.2s;
        svg {
            width: 100%;
            height: 100%;
        }
    }

    &:hover {
        border-color: #c7c7c7;

        i {
            color: #757575;
        }
    }
}

.popper-content {
    box-sizing: border-box;
    background: #ffffff;
    box-shadow: 0px 6px 12px 0px rgba(0, 0, 0, 0.12);
    border-radius: 8px;
    border: 1px solid #ebebeb;
    display: flex;
    width: calc(100vw - 48px);
    max-width: 934px;
    max-height: 576px;
    min-height: 300px;

    & > .loading {
        background: none;
    }
}

.template-product-nodata {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-family: Roboto-Regular, Roboto;
    font-weight: 400;
    color: #000000;
}

.template-product-aside {
    width: 136px;
    min-width: 136px;
    white-space: nowrap;
    padding-top: 12px;
    margin-left: 16px;
    margin-bottom: 16px;

    dt {
        margin-top: 4px;
        height: 34px;
        font-size: 14px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 34px;
        padding: 0 8px;
    }

    dd {
        height: 32px;
        margin-top: 4px;
        line-height: 32px;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        padding: 0 8px;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.2s;

        &:hover,
        &.active {
            background: #f0f0f0;
        }
    }
}

.template-product-list {
    flex: 1;
    padding: 16px 16px 16px 8px;
    overflow: auto;

    ul {
        display: flex;
        flex-wrap: wrap;
    }
    li {
        width: calc(33.3% - 12px);
        margin: 6px;
        padding-bottom: 12px;
        background: #f8f8f8;
        border-radius: 6px;
        border: 1px solid #f0f0f0;
        box-sizing: border-box;
        transition: all 0.2s;
        overflow: hidden;
        position: relative;
        cursor: pointer;

        &:hover {
            box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.1);
        }
    }

    figure {
        position: relative;
        background-color: #fff;
        border-bottom: 1px solid #f0f0f0;
        &::before {
            content: '';
            display: block;
            padding-bottom: 100%;
        }
        img {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
        }
    }

    h3 {
        margin-top: 8px;
        padding: 0 8px;
        min-height: 40px;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        line-height: 20px;
    }

    .level-discount {
        margin-top: 8px;
        padding: 0 8px;
        height: 18px;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        line-height: 18px;
        &::before {
            content: 'From';
            margin-right: 4px;
        }
    }

    p[name='size'] {
        margin-top: 8px;
        padding: 0 8px;
        height: 16px;
        font-size: 12px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #9e9e9e;
        line-height: 16px;
    }

    p[name='color'] {
        margin-top: 6px;
        display: flex;
        flex-wrap: wrap;
        padding: 0 6px;
        em {
            width: 12px;
            height: 12px;
            background: #5c323e;
            border-radius: 1px;
            border: 1px solid rgba(0, 0, 0, 0.16);
            box-sizing: border-box;
            margin: 2px;
        }
    }
}
</style>
